package com.test.javafaq_sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.test.javafaq_commons.entity.*;
import com.test.javafaq_commons.service.ServiceException;
import com.test.javafaq_sys.mapper.ClassroomMapper;
import com.test.javafaq_sys.mapper.UserMapper;
import com.test.javafaq_sys.mapper.UserRoleMapper;
import com.test.javafaq_sys.service.IUserService;
import com.test.javafaq_sys.vo.RegisterVo;
import com.test.javafaq_sys.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author test.com
 * @since 2025-04-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    ClassroomMapper classroomMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    private final List<User> teachers = new CopyOnWriteArrayList<>();

    private final Map<String,User> teachersMap = new ConcurrentHashMap<>();

//    @Autowired
//    IQuestionService questionService;

    //定时器
    private final Timer timer = new Timer();
    {
        //构造代码块执行优先于构造方法
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                synchronized (teachers){
                    teachers.clear();
                }
            }
        },1000*60*60,1000*60*60);
    }

//    @Override
//    public UserVo currentUserVo() {
//        //获得当前登陆用户名
//        String username = currentUsername();
//        //查询当前userVo
//        UserVo user = userMapper.findUserVoByUsername(username);
//        Integer count = questionService.countQuestionByUserId(user.getId());
//        //赋值
//        user.setQuestions(count);
//        return user;
//    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }

    @Override
    public List<Permission> getUserPermissions(Integer userId) {
        return userMapper.findUserPermissionById(userId);
    }

    @Override
    public List<Role> getUserRoles(Integer userId) {
        return userMapper.findUserRolesById(userId);
    }

    @Override
    public UserVo currentUserVo(String username) {
        UserVo user = userMapper.findUserVoByUsername(username);
        //查询用户提问数
        String url = "http://faq-service/v1/questions/count?userId={1}";
        Integer count = restTemplate.getForObject(url, Integer.class, user.getId());
        //赋值
        user.setQuestions(count);
        return user;
    }

    @Override
    public Map<String, User> getTeachersMap() {
        if(teachersMap.isEmpty()){
            getTeachers();
        }
        return teachersMap;
    }

    @Override
    public List<User> getTeachers() {
        if(teachers.isEmpty()){
            synchronized (teachers){
                if (teachers.isEmpty()){
                    // 0-》学生，1-》回答问题的老师
                    QueryWrapper<User> query = new QueryWrapper<>();
                    query.eq("type",1);
                    List<User> users = userMapper.selectList(query);
                    teachers.addAll(users);
                    //给map赋值
                    for (User u : teachers) {
                        teachersMap.put(u.getNickname(),u);
                    }
                    //查询出的一些关键信息清空；
                    for (User u : teachers) {
                        u.setPassword("");
                    }
                }
            }
        }
        return teachers;
    }

    @Override
    public String currentUsername() {
        //获取当前用户权限对象
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //确认当前用户是否登陆
        if(authentication instanceof AnonymousAuthenticationToken){
            throw ServiceException.invalidRequest("没登录!");
        }
        //登陆了
        String username = authentication.getName();
        return username;
    }

    @Override
    public void registerStudent(RegisterVo registerVo) {
        //判断registerVo是否为空
        if(registerVo == null){
            throw ServiceException.unprocesabelEntity("表单数据为空");
        }
        //根据邀请码查询处班级
        QueryWrapper<Classroom> query = new QueryWrapper<>();
        // JSD1912-876840   invite_code
        query.eq("invite_code",registerVo.getInviteCode());

        Classroom classroom = classroomMapper.selectOne(query);
        if(classroom == null){
            throw ServiceException.unprocesabelEntity("邀请码错误");
        }

        //验证用户名
        User u = userMapper.findUserByUsername(registerVo.getPhone());
        if(u != null){
            throw ServiceException.unprocesabelEntity("手机号已经注册");
        }
        //实例化要注册的对象
        User user = new User();
        user.setUsername(registerVo.getPhone());
        user.setPhone(registerVo.getPhone());
        user.setNickname(registerVo.getNickname());
        user.setPassword("{bcrypt}" + passwordEncoder.encode(registerVo.getPassword()));
        user.setClassroomId(classroom.getId());
        user.setLocked(0);
        user.setEnabled(1);
        user.setCreatetime(LocalDateTime.now());

        //注册
        int num = userMapper.insert(user);
        if(num != 1){
            throw ServiceException.busy();
        }
        //为该对象添加角色
        UserRole userRole = new UserRole();
        userRole.setRoleId(2);
        userRole.setUserId(user.getId());
        num = userRoleMapper.insert(userRole);
        if(num != 1){
            throw ServiceException.busy();
        }
    }

    @Override
    public UserDetails getUserDetails(String username) {
        //根据用户民查询处用户对象
        User user = userMapper.findUserByUsername(username);
        //如果用户为空
        if(user == null){
            return null;
        }
        //根据id查用户权限
        List<Permission> ps = userMapper.findUserPermissionById(user.getId());
        //将查询到的所有权限 填装到一个数组中   auths
        int i = 0;
        String[] auths = new String[ps.size()];
        for(Permission p:ps){
            auths[i++] = p.getName();
        }
        //新增代码 --根据用户id查询角色
        List<Role> roles = userMapper.findUserRolesById(user.getId());
        //扩容auths
        auths = Arrays.copyOf(auths, auths.length + roles.size());
        for (Role r : roles) {
            auths[i++] = r.getName();
        }

        //UserDetails
        UserDetails u = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auths)
                //账号是否锁定
                .accountLocked(user.getLocked() == 1)
                //账号是否可用
                .disabled(user.getEnabled() == 0)
                .build();

        return u;
    }
}
